package cn.onesdream.app.api.security;

import cn.onesdream.app.api.service.UserService;
import cn.onesdream.app.dao.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
设置token过滤器,防止这个过滤器被调用多次
 * @author pc
 */
@Component
public class TokenAuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    private UserService userService;

    @Autowired
    private AppUserDetailsServiceImpl appUserDetailsServiceImpl;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        /**
        获取header中的验证信息
         */
        String authHeader = request.getHeader("token");
        /**
         * WebSocket连接的身份信息
         */
        String webSocketHeader = request.getHeader("Sec-WebSocket-Protocol");
        if (authHeader != null || webSocketHeader != null) {
            /**
            根据token中获取数据库中的用户信息
             */
            User user = userService.getUserByToken(authHeader);
            if (user == null){
                user = userService.getUserByToken(webSocketHeader);
            }
            if (user != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                /**
                根据用户名获取用户对象
                 */
                UserDetails userDetails = appUserDetailsServiceImpl.loadUserByUsername(user.getAccount());
                if (userDetails != null) {
                    UsernamePasswordAuthenticationToken authentication =
                            new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    /**
                    设置为已登录
                     */
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        if (webSocketHeader != null){
            response.setHeader("Sec-WebSocket-Protocol", webSocketHeader);
        }
        chain.doFilter(request, response);
    }
}
